// pages/index/index.js
const app = getApp()

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    dialogShow: false,
    dialogButtons: [
      { text: '取消' },
      { text: '确认' }
    ],
    roomId: null
  },
  onLoad() {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    this.getUserInfo()
  },
  getUserInfo () {
    wx.cloud.callFunction({
      name: 'drawsthFunctions',
      data: {
        url: 'user/getInfo'
      }
    }).then(res => {
      if (res.result) {
        const userInfo = res.result
        app.globalData.userInfo = userInfo
        this.setData({
          userInfo,
          hasUserInfo: true
        })
      }
      wx.hideLoading()
    })
  },
  setUserInfo (e) {
    const userInfo = e.detail.userInfo
    app.globalData.userInfo = userInfo
    this.setData({
      userInfo,
      hasUserInfo: true
    })
  },
  isUserPlaying () {
    wx.cloud.callFunction({
      name: 'drawsthFunctions',
      data: {
        url: 'room/isUserPlaying'
      }
    }).then(res => {
      const roomId = res.result
      if (roomId) {
        this.setData({
          dialogShow: true,
          roomId
        })
      } else {
        this.createRoom()
      }
    })
  },
  createRoom () {
    wx.cloud.callFunction({
      name: 'drawsthFunctions',
      data: {
        url: 'room/add',
        data: {
          userInfo: this.data.userInfo
        }
      }
    }).then(res => {
      const roomId = res.result._id
      wx.redirectTo({
        url: `/pages/room/room?roomId=${roomId}`
      })
    })
  },
  tapDialogButton ({ detail }) {
    if (detail.index === 1) {
      wx.redirectTo({
        url: `/pages/room/room?roomId=${this.data.roomId}`
      })
    } else {
      this.setData({
        dialogShow: false
      })
    }
  }
})
